package app.engine.solucoes.request.command;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import app.engine.solucoes.request.beans.Pergunta;
import app.engine.solucoes.request.beans.Resposta;
import app.engine.solucoes.request.dao.AppDAO;
import app.engine.solucoes.request.exception.CommandException;

public class ViewQuestionCommand implements Command {

	private String next;
	
	public ViewQuestionCommand(String next) {
		super();
		this.next = next;
	}
	
	@Override
	public String execute(HttpServletRequest req) throws CommandException {
		AppDAO dao = new AppDAO();
		Long idPergunta = Long.parseLong(req.getParameter("idPergunta"));
		List<Object> respostas = dao.selectAll(Resposta.class);
		for (Iterator<?> iterator = respostas.iterator(); iterator.hasNext();) {
			Resposta resposta = (Resposta) iterator.next();
			if (!resposta.getIdPergunta().equals(idPergunta) || !resposta.getAprovada()) {
				iterator.remove();
			}
		}
		Pergunta pergunta = (Pergunta) dao.select(Pergunta.class, idPergunta);
		req.setAttribute("pergunta", pergunta);
		req.setAttribute("txtPergunta", req.getParameter("txtPergunta"));
		req.getSession().setAttribute("respostas", respostas);
		return next;
	}

}
